package persistence.product;

import java.io.*;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Product;

public class ProductDAOFile implements ProductDAO {

    private String fileName;
    private static ProductDAOFile persistenceManager = null;

    private ProductDAOFile() {
    }

    public static ProductDAO getJDBCPersistenceManager() {
        if (persistenceManager == null) {
            persistenceManager = new ProductDAOFile();
        }
        return persistenceManager;
    }

    @Override
    public boolean setUp(String url, String driver, String user, String password) {
        this.fileName = "fileName";
        try {
            File fileProduct = new File(fileName + "productos.txt");
            if (!fileProduct.exists()) {
                return true;
            }
            InputStream inputStream = new FileInputStream(fileProduct);
            ObjectInputStream objectInputStreamProductos = new ObjectInputStream(inputStream);
            int numberOfProducts = (Integer) objectInputStreamProductos.readObject();
            for (int i = 0; i < numberOfProducts; i++) {
                Product product = (Product) objectInputStreamProductos.readObject();
                productMap.put(product.getId(), product);
            }
            objectInputStreamProductos.close();
        } catch (Exception ex) {
            Logger.getLogger(ProductDAOFile.class.getName()).log(Level.SEVERE,
                    "No se pudieron cargar los datos del archivo de productos", ex);
            return false;
        }
        return true;
    }

    @Override
    public void setUpMap() {
    }

    @Override
    public boolean disconnect() {
        try {
            OutputStream outputStreamProducts = new FileOutputStream(new File(fileName + "productos.txt"));
            ObjectOutputStream objectOutputStreamProducts = new ObjectOutputStream(outputStreamProducts);
            objectOutputStreamProducts.writeObject(productMap.size());
            for (Product product : productMap.values()) {
                objectOutputStreamProducts.writeObject(product);
            }
            objectOutputStreamProducts.close();
        } catch (IOException ex) {
            Logger.getLogger(ProductDAOFile.class.getName()).log(Level.SEVERE,
                    "No se pudieron guardar los datos en el archivo de productos", ex);
            return false;
        }

        return true;
    }

    @Override
    public synchronized boolean createProduct(Product product) {
        product.setId(product.getNombre() + "_" + product.getSo());
        if (productMap.containsKey(product.getId())) {
            return false;
        } else {
            productMap.put(product.getId(), product);
            return true;
        }
    }

    @Override
    public synchronized boolean deleteProduct(String name) {
        if (!productMap.containsKey(name)) {
            return false;
        } else {
            productMap.remove(name);
            return true;
        }
    }

    @Override
    public synchronized boolean updateProduct(String name, Product product) {
        if (!productMap.containsKey(name)) {
            return false;
        } else if(!name.equals(product.getNombre() + "_" + product.getSo())){
            return false;
        } else {
            product.setId(product.getNombre() + "_" + product.getSo());
            productMap.put(product.getId(), product);
            return true;
        }
    }

    @Override
    public synchronized void readProduct(String name, Map<String, Product> productArray) {
        Product product = productMap.get(name);
        if (product != null) {
            productArray.put(product.getId(), product);
            return;
        }
        product = productMap.get(name + "_iOS");
        if (product != null) {
            productArray.put(product.getId(), product);
        }
        product = productMap.get(name + "_Android");
        if (product != null) {
            productArray.put(product.getId(), product);
        }
        product = productMap.get(name + "_Blackberry");
        if (product != null) {
            productArray.put(product.getId(), product);
        }
        product = productMap.get(name + "_Windows Phone");
        if (product != null) {
            productArray.put(product.getId(), product);
        }
    }

    @Override
    public synchronized void readAllProducts(Map<Integer, Product> productArray, String so) {
        Iterator itr = productMap.entrySet().iterator();
        if (so == null) {
            for (int i = 1; itr.hasNext(); i++) {
                Map.Entry e = (Map.Entry) itr.next();
                productArray.put(i, (Product) e.getValue());
            }
        } else {
            String s;
            for (int i = 1; itr.hasNext();) {
                Map.Entry e = (Map.Entry) itr.next();
                s = (String) e.getKey();
                if (s.contains(so)) {
                    productArray.put(i, (Product) e.getValue());
                    i++;
                }
            }
        }
    }

    @Override
    public synchronized int readPageProducts(Map<Integer, Product> productArray, String so, int pagina) {
        Iterator itr = productMap.entrySet().iterator();
        if (so == null) {
            for (int i = 1; i < (pagina*2)-1 && itr.hasNext(); i++){
                itr.next();
            }
            for (int i = 1; i < 3 &&itr.hasNext(); i++) {
                Map.Entry e = (Map.Entry) itr.next();
                productArray.put(i, (Product) e.getValue());
            }
        } else {
            String s;
            for (int i = 1; i < (pagina*2)-1 && itr.hasNext(); ){
                s = (String) ((Map.Entry) itr.next()).getKey();
                if (s.contains(so))
                    i++;
            }
            for (int i = 1; i < 3 && itr.hasNext(); ) {
                Map.Entry e = (Map.Entry) itr.next();
                s = (String) e.getKey();
                if (s.contains(so)) {
                    productArray.put(i, (Product) e.getValue());
                    i++;
                }
            }
        }
        return productMap.size();
    }
}
